package com.spzx.product.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.spzx.common.core.constant.Constants;
import com.spzx.common.security.utils.SecurityUtils;
import com.spzx.product.domain.Product;
import com.spzx.product.domain.ProductDetails;
import com.spzx.product.domain.ProductSku;
import com.spzx.product.domain.SkuStock;
import com.spzx.product.mapper.ProductDetailsMapper;
import com.spzx.product.mapper.ProductMapper;
import com.spzx.product.mapper.ProductSkuMapper;
import com.spzx.product.mapper.SkuStockMapper;
import com.spzx.product.service.ProductService;
import jakarta.annotation.Resource;
import org.redisson.api.RBloomFilter;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Arrays;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @ClassName ProductServiceImpl
 * @Author 波
 * @Date 2024/7/29 21:17
 */
@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper, Product> implements ProductService {
    @Resource
    private ProductSkuMapper productSkuMapper;
    @Resource
    private ProductDetailsMapper productDetailsMapper;
    @Resource
    private SkuStockMapper skuStockMapper;

    @Resource
    private RedissonClient redissonClient;
    /**
     * 获取商品分页信息
     * @param product 传入查询的条件
     * @return List<Product>
     */
    @Override
    public List<Product> getProductPageList(Product product) {
        return baseMapper.getProductPageList(product);
    }

    /**
     * 新增商品信息
     * @param product 传入的数据
     * @return 受影响的行数
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int addProduct(Product product) {
        this.save(product);
        product.setCreateBy(SecurityUtils.getUsername());
        List<ProductSku> productSkuList = product.getProductSkuList();
        for(int i = 0 ; i < productSkuList.size() ; i++){
            ProductSku productSku = productSkuList.get(i);
            productSku.setProductId(product.getId());
            productSku.setSkuCode(product.getId()+"_"+i);
            productSku.setSkuName(product.getName()+" "+productSku.getSkuSpec());
            productSkuMapper.insert(productSku);

            SkuStock skuStock = new SkuStock();
            skuStock.setSkuId(productSku.getId());
            skuStock.setTotalNum(productSku.getStockNum());
            skuStock.setLockNum(0);
            skuStock.setAvailableNum(productSku.getStockNum());
            skuStock.setSaleNum(0);
            skuStockMapper.insert(skuStock);
        }
        ProductDetails productDetails = new ProductDetails();
        productDetails.setProductId(product.getId());
        productDetails.setImageUrls(String.join(",",product.getDetailsImageUrlList()));
        productDetailsMapper.insert(productDetails);

        return product.getId().intValue();
    }

    /**
     * 根据id获取商品详情信息
     * @param id id
     * @return Product
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public Product selectProductDetailInfoById(Long id) {
        Product product = this.getById(id);
        //根据id查询ProductSku列表
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId,id));
        List<SkuStock> skuStockList=skuStockMapper.selectList(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId,productSkuList).select(SkuStock::getSkuId,SkuStock::getTotalNum));
        Map<Long, Integer> skuIdToStockNumMap = skuStockList.stream().collect(Collectors.toMap(SkuStock::getSkuId, SkuStock::getTotalNum));
        productSkuList.forEach(item -> {
            item.setStockNum(skuIdToStockNumMap.get(item.getId()));
        });
        product.setProductSkuList(productSkuList);
        //商品详情
        ProductDetails productDetails = productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, id));
        product.setDetailsImageUrlList(Arrays.asList(productDetails.getImageUrls().split(",")));
        return product;
    }
    /**
     * 修改商品信息
     * @param product 修改后的对象
     * @return 受影响的行数
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int updateProduct(Product product) {
        //先修改基本的product信息
        this.updateById(product);
        product.setUpdateBy(SecurityUtils.getUsername());
        List<ProductSku> productSkuList = product.getProductSkuList();
        productSkuList.forEach(productSku -> {
            //修改商品SKU信息
            productSkuMapper.updateById(productSku);

            //修改商品库存
            SkuStock skuStock = skuStockMapper.selectOne(new LambdaQueryWrapper<SkuStock>().eq(SkuStock::getSkuId, productSku.getId()));
            skuStock.setTotalNum(productSku.getStockNum());
            int availableNum = skuStock.getTotalNum() - skuStock.getLockNum();
            skuStock.setAvailableNum(availableNum);
            skuStockMapper.updateById(skuStock);
        });

        //修改商品详细信息
        ProductDetails productDetails = productDetailsMapper.selectOne(new LambdaQueryWrapper<ProductDetails>().eq(ProductDetails::getProductId, product.getId()));
        productDetails.setImageUrls(String.join(",", product.getDetailsImageUrlList()));
        productDetailsMapper.updateById(productDetails);
        return 1;
    }
    /**
     * 删除商品详情信息
     * @param ids 传入的Id
     * @return 受影响的行数
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public int deleteProductByIds(Long[] ids) {
        baseMapper.deleteBatchIds(Arrays.asList(ids));
        List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, ids).select(ProductSku::getId));
        List<Long> skuIdList = productSkuList.stream().map(ProductSku::getId).collect(Collectors.toList());
        productSkuMapper.delete(new LambdaQueryWrapper<ProductSku>().in(ProductSku::getProductId, ids));
        skuStockMapper.delete(new LambdaQueryWrapper<SkuStock>().in(SkuStock::getSkuId, skuIdList));
        productDetailsMapper.delete(new LambdaQueryWrapper<ProductDetails>().in(ProductDetails::getProductId, ids));
        return 1;
    }

    @Override
    public void updateAuditStatus(Long id, Integer auditStatus) {
        Product product = new Product();
        product.setUpdateBy(SecurityUtils.getUsername());
        product.setId(id);
        if(auditStatus==1){
            product.setAuditStatus(1);
            product.setAuditMessage("审核通过！");
        }else{
            product.setAuditStatus(-1);
            product.setAuditMessage("审核不通过");
        }
        baseMapper.updateById(product);
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public void updateStatus(Long id, Integer status) {
        Product product = new Product();
        product.setUpdateBy(SecurityUtils.getUsername());
        product.setId(id);
        if(status == 1) {
            product.setStatus(1);
            //获取布隆过滤器
            RBloomFilter<Object> bloomFilter = redissonClient.getBloomFilter(Constants.PRODUCT_BLOOM_FILTER_NAME);
            List<ProductSku> productSkuList = productSkuMapper.selectList(new LambdaQueryWrapper<ProductSku>().eq(ProductSku::getProductId, id));
            productSkuList.forEach(item -> {
                bloomFilter.add(item.getId());
            });
        } else {
            product.setStatus(-1);
        }
        baseMapper.updateById(product);
    }



}
